require 'net/http'
require 'net/https'
require 'uri'

module Provider

  class OrangeCH < AbstractProvider

    @sms_sender

    @login_name
    @password
    
    def initialize(sms_sender)
      @sms_sender = sms_sender
      @login_name = @sms_sender.get_main.login_name
      @password = @sms_sender.get_main.password
    end

    def send(to, text)
      use_ssl = 0

      trans =Iconv.new('ISO-8859-1','UTF-8') # new converter-object encoding from UTF-8 to ISO-8859-1
      text=URI.escape(trans.iconv(text)) # convert message to ISO-8859-1 and escape it for use in URL

      #SmsWidget::Main.logger.debug "login = #{login}\npassword = #{password}\nto = #{to}\ntext = #{text}\nuse_ssl = #{use_ssl}"

      # URLs
      referer_url = 'http://www.orange.ch'
      login_url = 'https://www.orange.ch/footer/login/loginForm'
      send_url = 'https://www.orange.ch/myorange/sms/smsForm'

      # Settings
      user_agent = "Orange.ch SMS Widget"
      cookie = ''
      if use_ssl
        port = 443
      else
        port = 80
      end

      # Now do the login
      login_uri = URI.parse(login_url)

      http = Net::HTTP.new(login_uri.host, port)
      http.use_ssl = use_ssl
      post_data = "wui_target_id=loginButton&wui_event_id=onclick&username=#{@login_name}&password=#{@password}&loginButton=Login";
      post_headers = { 'Referer' => referer_url, 'Cookie' => cookie, 'Content-Type' => 'application/x-www-form-urlencoded'}

      resp, data = http.post(login_uri.path, post_data, post_headers)
      resp.each { |key, val|
        #SmsWidget::Main.logger.debug "#{key} => #{val}"
      if key == 'set-cookie'
          cookie = val
          SmsWidget::Main.logger.info 'accepted cookie: ' + val
      end
      }
      #SmsWidget::Main.logger.debug "orange ch login data: #{data}"
      if data.include? '<div class="error" id="errorList">'
        raise InvalidPasswordOrUsernameException
      end

        #now we can send the message
        send_uri = URI.parse(send_url)

        http = Net::HTTP.new(send_uri.host, port)
        http.use_ssl = use_ssl
        post_data = "wui_target_id=sendButton&wui_event_id=onclick&destinationNumberInput=#{to}&messageInput=#{text}&charNumberLeftOutput=0&signatureInput="
        post_headers = { 'Referer' =>  login_url, 'Cookie' => cookie, 'Content-Type' => 'application/x-www-form-urlencoded'}


        sent=false

        resp, data = http.post(send_uri.path, post_data, post_headers)
        data.each { |line|
          if line =~ /successOutput/
            #exit 0
            sms_sent()
            sent=true
          end
        }
          unless sent
            sms_not_sent("Wrong username or password?")
          end
      end
      


  end
    
end
